<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            :rules="queryRules"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="姓名" prop="realName">
                <el-input
                    v-model="queryParams.realName"
                    placeholder=""
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item
                v-if="$store.getters.allDefectObj['HR-WEB-145'] == 1"
                label="部门名称"
                prop="deptName"
            >
                <el-input
                    v-model="queryParams.deptName"
                    placeholder=""
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item v-else label="部门名称" prop="deptId">
                <treeselect
                    v-model="queryParams.deptId"
                    :options="deptOptions"
                    :show-count="true"
                    placeholder=""
                    @keyup.enter.native="handleQuery"
                    style="width: 215px"
                />
            </el-form-item>

            <el-form-item label="年度" prop="year">
                <el-input
                    v-model.trim.number="queryParams.year"
                    placeholder=""
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['hrm:record:add']"
                        >新增</el-button
                    >
                </el-col>
            </el-row>

            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="recordList"
                @selection-change="handleSelectionChange"
            >
                <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                ></el-table-column>
                <el-table-column label="姓名" align="center" prop="realName" />

                <el-table-column label="部门" align="center" prop="deptName" />
                <el-table-column
                    label="考核模板"
                    align="center"
                    prop="modelName"
                />
                <el-table-column label="总分" align="center" prop="score" />
                <el-table-column label="年度" align="center" prop="year" />

                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['hrm:record:edit']"
                            >修改</el-button
                        >

                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['hrm:record:remove']"
                            >删除</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleView(scope.row)"
                            v-hasPermi="['hrm:record:edit']"
                            >查看</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total > 10"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加或修改年度考核记录对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="1200px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="boolView ? [] : rules"
                    label-width="120px"
                >
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="部门" prop="deptId">
                                <treeselect
                                    :disabled="
                                        (boolView || form.realName) &&
                                        $store.getters.allDefectObj[
                                            'HR-WEB-148'
                                        ] == 1
                                    "
                                    v-model="form.deptId"
                                    :options="deptOptions"
                                    :show-count="true"
                                    @change="setDeptId"
                                    placeholder="请选择归属部门"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="岗位" prop="postId">
                                <el-select
                                    :disabled="
                                        (boolView || form.realName) &&
                                        $store.getters.allDefectObj[
                                            'HR-WEB-148'
                                        ] == 1
                                    "
                                    v-model="form.postId"
                                    placeholder="请选择岗位"
                                    clearable
                                    @change="setPostId"
                                >
                                    <el-option
                                        v-for="item in postList"
                                        :key="item.postId"
                                        :label="item.postName"
                                        :value="item.postId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="用户" prop="realName">
                                <el-input
                                    :disabled="
                                        boolView &&
                                        $store.getters.allDefectObj[
                                            'HR-WEB-148'
                                        ] == 1
                                    "
                                    suffix-icon="el-icon-search"
                                    readonly
                                    @focus="openSecelctOneUser"
                                    v-model="form.realName"
                                    placeholder="请选择用户"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label="模板名称" prop="modelId">
                                <el-select
                                    :disabled="
                                        boolView &&
                                        $store.getters.allDefectObj[
                                            'HR-WEB-148'
                                        ] == 1
                                    "
                                    v-model="form.modelId"
                                    @change="changeModel"
                                >
                                    <el-option
                                        v-for="item in modelList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="适用日期">
                                <el-input disabled v-model="form.year" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!-- <el-form-item label="用户ID" prop="userId">
                        <el-input
                            v-model="form.userId"
                            placeholder="请输入用户ID"
                        />
                    </el-form-item>
                    <el-form-item label="员工编号" prop="staffNum">
                        <el-input
                            v-model="form.staffNum"
                            placeholder="请输入员工编号"
                        />
                    </el-form-item>
                    <el-form-item label="部门ID" prop="deptId">
                        <el-input
                            v-model="form.deptId"
                            placeholder="请输入部门ID"
                        />
                    </el-form-item>
                    <el-form-item label="部门" prop="deptName">
                        <el-input
                            v-model="form.deptName"
                            placeholder="请输入部门"
                        />
                    </el-form-item>
                    <el-form-item label="所属组织id" prop="orgId">
                        <el-input
                            v-model="form.orgId"
                            placeholder="请输入所属组织id"
                        />
                    </el-form-item>
                    <el-form-item label="所属岗位的ID字符串" prop="postId">
                        <el-input
                            v-model="form.postId"
                            placeholder="请输入所属岗位的ID字符串"
                        />
                    </el-form-item>
                    <el-form-item label="岗位" prop="postName">
                        <el-input
                            v-model="form.postName"
                            placeholder="请输入岗位"
                        />
                    </el-form-item>
                    <el-form-item label="年度" prop="year">
                        <el-input
                            v-model="form.year"
                            placeholder="请输入年度"
                        />
                    </el-form-item>
                    <el-form-item label="分值" prop="score">
                        <el-input
                            v-model="form.score"
                            placeholder="请输入分值"
                        />
                    </el-form-item> -->
                    <el-divider content-position="center"
                        >标内容及打分列表</el-divider
                    >
                    <!-- <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button
                                type="primary"
                                icon="el-icon-plus"
                                size="mini"
                                @click="handleAddHrmAppraiseItemRecord"
                                >添加</el-button
                            >
                        </el-col>
                        <el-col :span="1.5">
                            <el-button
                                type="danger"
                                icon="el-icon-delete"
                                size="mini"
                                @click="handleDeleteHrmAppraiseItemRecord"
                                >删除</el-button
                            >
                        </el-col>
                    </el-row> -->
                    <el-table
                        style="width: 100%"
                        :border="Global.tableShowBorder"
                        :data="hrmAppraiseItemRecordList"
                        :row-class-name="rowHrmAppraiseItemRecordIndex"
                        @selection-change="
                            handleHrmAppraiseItemRecordSelectionChange
                        "
                        ref="hrmAppraiseItemRecord"
                    >
                        <!-- <el-table-column
                            type="selection"
                            width="50"
                            align="center"
                        /> -->
                        <el-table-column
                            label="序号"
                            align="center"
                            prop="index"
                            width="50"
                        />
                        <el-table-column label="指标名称" prop="name">
                            <template slot-scope="scope">
                                <el-input
                                    disabled
                                    v-model="scope.row.name"
                                    placeholder="请输入指标名称"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="指标描述" prop="describe">
                            <template slot-scope="scope">
                                <el-input
                                    disabled
                                    v-model="scope.row.describe"
                                    placeholder="请输入指标描述"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="考核方向" prop="purpose">
                            <template slot-scope="scope">
                                <el-input
                                    disabled
                                    v-model="scope.row.purpose"
                                    placeholder="请输入考核方向"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="分值" prop="score">
                            <template slot-scope="scope">
                                <el-input-number
                                    :disabled="
                                        boolView &&
                                        $store.getters.allDefectObj[
                                            'HR-WEB-148'
                                        ] == 1
                                    "
                                    :precision="0"
                                    :max="
                                        $store.getters.allDefectObj[
                                            'HR-WEB-147'
                                        ] == 0 && !form.id
                                            ? Infinity
                                            : 100
                                    "
                                    :min="
                                        $store.getters.allDefectObj[
                                            'HR-WEB-147'
                                        ] == 0 && !form.id
                                            ? -Infinity
                                            : 0
                                    "
                                    controls-position="right"
                                    v-model="scope.row.score"
                                    placeholder="请输入分值"
                                />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button v-if="!boolView" type="primary" @click="submitForm"
                    >提 交</el-button
                >
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <userTableDialog
            title="员工列表"
            :defaultParams="defaultParams"
            :open.sync="showUserTableVision"
            @confirm="setBaseInfo"
        >
        </userTableDialog>
    </div>
</template>

<script>
import {
    listRecord,
    getRecord,
    delRecord,
    addRecord,
    updateRecord,
} from "@/api/hrm/record";
import { listInduction } from "@/api/hrm/staff/induction";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listPostAll } from "@/api/system/post";

import {
    listModel,
    getModel,
    delModel,
    addModel,
    updateModel,
    addRelation,
    delRelation,
} from "@/api/hrm/model";

export default {
    name: "Record",
    data() {
        return {
            //员工信息弹窗
            defaultParams: {
                isLink: true,
                staffTypes: "0,1,2,4",
            },
            showUserTableVision: false,

            //部门
            // 职位选项
            postList: [],
            // 部门树选项
            deptOptions: [],
            deptOptionsArray: null,

            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 子表选中数据
            checkedHrmAppraiseItemRecord: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 年度考核记录表格数据
            recordList: [],
            // 考核项目记录表格数据
            hrmAppraiseItemRecordList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                deptName: null,

                isAsc: "descending",
                realName: null,
                userId: null,
                staffNum: null,
                deptId: null,
                deptName: null,
                orgId: null,
                postId: null,
                postName: null,
                year: null,
                score: null,
            },
            // 表单参数
            form: {},
            queryRules: {
                year: [
                    //只能是四位数字
                    {
                        pattern: /^\d{4}$/,
                        message: "请输入四位数字",
                        trigger: "blur",
                    },
                ],
            },

            // 表单校验
            rules: {
                deptId: [
                    {
                        required: true,
                        message: "请选择部门",
                        trigger: "change",
                    },
                ],
                postId: [
                    {
                        required: true,
                        message: "请选择岗位",
                        trigger: "change",
                    },
                ],
                realName: [
                    {
                        required: true,
                        message: "请选择员工",
                        trigger: "change",
                    },
                ],
                modelId: [
                    {
                        required: true,
                        message: "请选择模板",
                        trigger: "change",
                    },
                ],
            },
            modelList: [],
            boolView: false,
        };
    },
    components: { Treeselect },
    created() {
        this.getList();
        this.getTreeselect();
        this.getPostList();
        this.getModelList();
    },
    methods: {
        //匹配选中的模板带入考核记录
        changeModel(val) {
            let obj = this.modelList.find((item) => item.id == val);
            this.form.modelName = obj.name;
            this.form.year = obj.year;
            this.hrmAppraiseItemRecordList = obj.items.map((item) => {
                delete item.id;

                return {
                    ...item,
                    describe: item.desc,
                    year: obj.year,
                };
            });
        },
        //获取所有的模板
        getModelList() {
            listModel({ pageNum: 1, pageSize: 100, isAsc: "descending" }).then(
                (response) => {
                    this.modelList = response.rows;
                }
            );
        },

        //查询参数联动
        setDeptId(id) {
            this.defaultParams.deptId = id;
            this.form.userId = null;
            this.form.realName = null;
        },
        //查询参数联动
        setPostId(id) {
            this.defaultParams.postId = id;
            this.form.userId = null;
            this.form.realName = null;
        },
        //唤醒员工弹窗
        openSecelctOneUser() {
            this.showUserTableVision = true;
        },

        // 设置选中的基础信息
        setBaseInfo(row) {
            this.form.userId = row.userId;
            this.form.realName = row.realName;
            this.form.staffNum = row.staffNum;

            if (
                this.$store.getters.allDefectObj["HR-WEB-146"] == 1 &&
                !this.form.id
            ) {
                this.form.deptId = row.deptId;
                this.form.orgId = row.orgId;
                if (row.postId) {
                    let temp = row.postId.split(",");
                    if (temp.length > 0) {
                        this.form.postId = Number(temp[0]);
                    }
                }
                this.form.deptName = this.parseSelectTree(this.form.deptId);
                this.form.postName = this.parsePostName(this.form.postId);
            }
        },
        parsePostName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let obj = this.postList.find((item) => item.postId == ids);
                if (obj) {
                    return obj.postName;
                }
            }
            return "—";
        },
        getUserList() {
            listInduction({ deptId: this.form.deptId }).then((response) => {
                this.recordList = response.data;
            });
        },
        getPostList() {
            listPostAll().then((res) => {
                this.postList = res.data;
            });
        },

        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                this.deptOptionsArray = this.flattenArray(this.deptOptions);
            });
        },
        flattenArray(arr) {
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                result.push(item);
                if (item.children) {
                    result = result.concat(this.flattenArray(item.children));
                }
            }
            return result;
        },
        parseSelectTree(id) {
            console.log(this.deptOptionsArray, "this.deptOptionsArray");
            let tempObj = this.deptOptionsArray.find((item) => item.id == id);
            if (tempObj) {
                return tempObj.label;
            }
            return "—";
        },
        setFormBase(row) {
            let temp = { ...row };
            console.log(temp, "temp");
            // 带入姓名 用户id  部门id 部门 所属岗位
            this.form.deptId = temp.deptId;
            this.form.userId = temp.userId;
            this.form.orgId = temp.orgId;
            this.form.staffNum = temp.staffNum;
            this.form.postId = [];

            if (temp.postId) {
                let tempList = temp.postId.split(",");
                tempList.forEach((item) => {
                    this.form.postId.push(Number(item));
                });
            }

            this.form.sex = temp.sex;
            this.form.staffType = temp.staffType;

            this.form.type = "0";
            this.$set(this.form, "realName", temp.realName);
        },

        /** 查询年度考核记录列表 */
        getList() {
            this.loading = true;
            listRecord(this.queryParams).then((response) => {
                this.recordList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                realName: null,
                userId: null,
                staffNum: null,
                deptId: null,
                deptName: null,
                orgId: null,
                postId: null,
                postName: null,
                year: null,
                score: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
            };
            this.boolView = false;
            this.queryParams = {};
            this.hrmAppraiseItemRecordList = [];
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.$refs["queryForm"].validate((valid) => {
                if (valid) {
                    this.queryParams.pageNum = 1;
                    this.getList();
                }
            });
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加绩效表";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getRecord(id).then((response) => {
                this.form = response.data;
                this.form.deptId = Number(this.form.deptId);
                this.form.postId = Number(this.form.postId);
                this.form.modelId = Number(this.form.modelId);
                this.hrmAppraiseItemRecordList =
                    response.data.hrmAppraiseItemRecordList;
                this.open = true;
                this.title = "修改绩效表";
            });
        },
        handleView(row) {
            this.reset();
            const id = row.id || this.ids;
            getRecord(id).then((response) => {
                this.form = response.data;
                this.form.deptId = Number(this.form.deptId);
                this.form.postId = Number(this.form.postId);
                this.form.modelId = Number(this.form.modelId);
                this.hrmAppraiseItemRecordList =
                    response.data.hrmAppraiseItemRecordList;
                this.boolView = true;
                this.open = true;
                this.title = "查看绩效表";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.hrmAppraiseItemRecordList) {
                        for (
                            let i = 0;
                            i < this.hrmAppraiseItemRecordList.length;
                            i++
                        ) {
                            if (!this.hrmAppraiseItemRecordList[i].score) {
                                this.$modal.msgError("请填写考核得分");
                                return;
                            }
                        }
                    }
                    this.form.hrmAppraiseItemRecordList =
                        this.hrmAppraiseItemRecordList;

                    if (this.form.id != null) {
                        updateRecord(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addRecord(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm("绩效表删除后不可恢复，确认删除？")
                .then(function () {
                    return delRecord(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("已经完成删除！");
                })
                .catch(() => {
                    if (this.$store.getters.allDefectObj["HR-WEB-149"] == 0) {
                        delRecord(ids).then(() => {
                            this.getList();
                            this.$modal.msgSuccess("已经完成删除！");
                        });
                    }
                });
        },
        /** 考核项目记录序号 */
        rowHrmAppraiseItemRecordIndex({ row, rowIndex }) {
            row.index = rowIndex + 1;
        },
        /** 考核项目记录添加按钮操作 */
        handleAddHrmAppraiseItemRecord() {
            let obj = {};
            obj.name = "";
            obj.describe = "";
            obj.purpose = "";
            obj.score = "";
            obj.year = "";
            this.hrmAppraiseItemRecordList.push(obj);
        },
        /** 考核项目记录删除按钮操作 */
        handleDeleteHrmAppraiseItemRecord() {
            if (this.checkedHrmAppraiseItemRecord.length == 0) {
                this.$modal.msgError("请先选择要删除的考核项目记录数据");
            } else {
                const hrmAppraiseItemRecordList =
                    this.hrmAppraiseItemRecordList;
                const checkedHrmAppraiseItemRecord =
                    this.checkedHrmAppraiseItemRecord;
                this.hrmAppraiseItemRecordList =
                    hrmAppraiseItemRecordList.filter(function (item) {
                        return (
                            checkedHrmAppraiseItemRecord.indexOf(item.index) ==
                            -1
                        );
                    });
            }
        },
        /** 复选框选中数据 */
        handleHrmAppraiseItemRecordSelectionChange(selection) {
            this.checkedHrmAppraiseItemRecord = selection.map(
                (item) => item.index
            );
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                "hrm/record/export",
                {
                    ...this.queryParams,
                },
                `record_${new Date().getTime()}.xlsx`
            );
        },
    },
};
</script>
